<?php
/**
 * FastApp.
 * 10/17/24
 * @Author 深色的海 (wx:deepsea_0024)
 * @Contact telegram:deepsea159 
 */

namespace App\Fastapp\Api\Service\Comm;

use App\Fastapp\Model\Message;
use App\Fastapp\Model\MessageRead;

class MessageService
{
    public function type(): array
    {
        $res = api_cache()->getDictByKey('message_type');
        $num = [];
        try {
            $uid = get_uid();
            $read = MessageRead::query()->where(['user_id' => $uid])->pluck('object_id', 'type')->toArray();
            $w = '';
            foreach ($res as $item) {
                $id = $read[$item['value']] ?? 0;
                $w .= ' or (type=' . $item['value'] . " and id>$id)";
            }
            $num = Message::query()->selectRaw('type,count(*) as num')->whereRaw(substr($w, 3))->groupBy('type')->pluck('num', 'type')->toArray();
        } catch (\Throwable) {
        }
        $list = [];
        foreach ($res as $item) {
            $item['unread'] = empty($num[$item['value']]) ? 0 : $num[$item['value']];
            $list[] = $item;
        }
        return ['list' => $list];
    }

    public function list(int $account_type, int $type): array
    {
        $list = Message::query()->where(['account_type' => $account_type, 'type' => $type])
            ->orderByDesc('id')
            ->select(['id', 'type', 'object_type', 'object_id', 'url', 'title', 'image', 'desc', 'content'])
            ->get()->map(function ($item) {
                $item->title = fastapp_lang_text($item->title);
                $item->image = fastapp_lang_text($item->image);
                $item->desc = fastapp_lang_text($item->desc);
                $item->content = fastapp_lang_text($item->content);
                return $item;
            });
        $max_id = 0;
        try {
            $uid = get_uid();
            $md = MessageRead::query()->firstOrCreate(['user_id' => $uid, 'type' => $type]);
            $max_id = $md->object_id ?: 0;
            if ($list->first()) $md->update(['object_id' => $list->first()->id]);
        } catch (\Throwable) {
        }
        return ['list' => $list, 'read_id' => $max_id];
    }

    public function detail(int $id): array
    {
        $item = Message::query()->select(['id', 'type', 'object_type', 'object_id', 'url', 'title', 'image', 'desc', 'content'])->where(['id' => $id])->firstOrFail();
        $item->title = fastapp_lang_text($item->title);
        $item->image = fastapp_lang_text($item->image);
        $item->desc = fastapp_lang_text($item->desc);
        $item->content = fastapp_lang_text($item->content);
        return $item->toArray();
    }
}